<template>
    <el-dialog class="ui-rackon-dlg" top="5vh" :close-on-press-escape="false" :close-on-click-modal="false" v-model="dialogVisible" :title="dialogTitle" ref="dialog" @opened="init" :beforeClose="beforeClose" @closed="finalThings">
        <div class="co-toolbar box-row">
            <el-form-item :label="isOn?'来源:':'目标:'">
                <el-select v-model="data.target_id">
                    <template v-for="item in stores">
                        <el-option v-if="item.id != storeId" :value="item.id" :label="item.name"></el-option>
                    </template>
                </el-select>
            </el-form-item>
            <span style="flex:1"></span>
            <el-form-item label="条件:" size="default" >
                <el-input class="co-search-input" placeholder="请输入商品名称或条码" v-model="params.code" clearable></el-input>
            </el-form-item>
            <el-button type="primary" @click="onSearch">查找</el-button>
        </div>
        <el-form :model="data" :rules="rules" ref="elForm" @submit.prevent="onSure" label-width="5.5rem">
            <el-table :data="filteredData" :height="'60vh'">
                <el-table-column prop="name" label="商品名">
                    <template v-slot:default="scope">
                        <el-icon size="18" @click="onRemoveItem(scope.row, $index)" style="cursor:pointer"><Delete /></el-icon>
                        <span style="vertical-align: text-bottom; padding-left:.25rem">{{ scope.row.name }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="store_num" :width="120" align="right">
                    <template #header>
                        <template v-if="isOn">来源数量</template>
                        <template v-else>当前数量</template>
                    </template>
                    <template v-slot:default="scope">
                        <template v-if="isOn">
                            <span>{{ scope.row.target_num - scope.row.op_num }}</span>
                        </template>
                        <template v-else>
                            <span>{{ scope.row.store_num - scope.row.op_num }}</span>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column prop="op_num" :width="120" align="center">
                    <template #header>
                        <template v-if="isOn">上架数量</template>
                        <template v-else>下架数量</template>
                    </template>
                    <template v-slot:default="scope">
                        <el-input-number class="op-num-ipt" size="default" :min="0" :max="isOn?scope.row.target_num:scope.row.store_num" v-model="scope.row.op_num" :step="1"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column prop="target_num" :width="120" align="right">
                    <template #header>
                        <template v-if="isOn">当前数量</template>
                        <template v-else>目标数量</template>
                    </template>
                    <template v-slot:default="scope">
                        <template v-if="isOn">
                            <span>{{ scope.row.store_num + scope.row.op_num }}</span>
                        </template>
                        <template v-else>
                            <span>{{ scope.row.target_num + scope.row.op_num }}</span>
                        </template>
                    </template>
                </el-table-column>
            </el-table>
            <div class="co-toolbar box-row">
                <el-form-item label="备注:" size="default" :label-width="60" class="memo-class">
                    <el-input v-model="data.data.desc" ></el-input>
                </el-form-item>
                <span style="flex:1"></span>
            </div>
        </el-form>
        <template #footer>
            <div class="box-row">
                <el-button size="default" type="success" @click="ExtraSelect">补选...</el-button>
                <div style="flex:1"></div>
                <el-button size="default" type="primary" @click="onSure">保存</el-button>
                <el-button size="default" type="danger" @click="onCancel">取消</el-button>
            </div>
        </template>
        <div v-loading="loading" :class="{'ui-dlg-loading':true, 'ui-dlg-loading-show': loading}" :element-loading-text="'请稍后...'"></div>
    </el-dialog>
</template>
<script>
import { reactive, computed, toRefs } from 'vue-demi';
import { Delete } from '@element-plus/icons-vue';
import { useSocket } from '../../uiframe/services/socket';
import { UiShowDialog } from '../../uiframe/layout/components/CompFactory.vue';
import ExtraSelectDialog from './ExtraSelectDialog.vue'
import { dict } from '../../uiframe/utils';
import { ElMessage, ElMessageBox } from 'element-plus';
export default {
    components:{
        Delete
    },
    props:{
        q:Object,
        done: Function,
        payload:Object,
        stores:Array,
        storeId:Number,
        mh:Number,
        isOn:Boolean
    },
    setup:(props)=>{
        let changed = false;
        const onmessage = (msg)=>ElMessage({message:msg.message, type:msg.success?'success':'error'}),
            isOn = props.isOn,storeId = props.storeId,stores = props.stores.filter(v=>v.id!=storeId),
            fromStore = props.stores.find(v=>v.id==storeId), isRack = fromStore.prop==1;

        const data = reactive({
            dialogVisible: true,
            isOn,
            stores,
            dialogTitle: computed(()=>{
                console.log(data.data.target_id);
                let target = stores.find(v=>v.id==data.data.target_id);
                if(target){
                    if(isOn){
                        return `从"${target.name}" 上架到 "${fromStore.name}"`
                    }else{
                        return `从"${fromStore.name}" 下架到 "${target.name}"`
                    }
                }
                return '';
            }),
            dialog: null,
            elForm: null,
            loading: false,
            filteredData: computed(()=>{
                return data.data.data.filter(v=>{
                    return !data.params.code || data.params.code.length==0 || v.name.indexOf(data.params.code)>=0 || v.code.indexOf(data.params.code)>=0;
                });
            }),
            data:{
                target_id: stores[0].id,
                src_id: storeId,
                data: [],
            },
            params: {
                code:''
            },
            h: computed(()=>{
                return props.mh - 322;
            }),
        }),rules =[

        ],
        renewSelected = ()=>{
            useSocket().then(socket=>socket.rpc('sel.get',{
                store_id: storeId,
                target_id: data.data.target_id,
                with_goods:true
            }).then(res=>{
                let dc =dict(data.data.data, 'id'), dc1 = dict(res.data, 'id'), del = [];
                // 增加新的
                res.data.forEach(v=>{
                    if(!dc[v.id]){
                        v.op_num = 0;
                        data.data.data.push(v);
                        changed = true;
                    }
                })
                // 删除取消了的
                data.data.data.forEach(v=>{
                    if(!dc1[v.id]){
                        del.push(v.id);
                        changed = true;
                    }
                })
                del.forEach(v=>data.data.data.splice(data.data.data.findIndex(v1=>v1.id==v),1))
            }).catch(res=>{

            }))
        },
        methods = {
            onSure:()=>{
                if(data.loading) return;
                data.loading = true;
                let payload = {
                    document_type: isOn ? 2 : 3, // 2 上架 3 下架
                    source_id: isOn? data.data.target_id : storeId,
                    target_id: isOn? storeId : data.data.target_id,
                    desc: data.data.desc ?? '',
                    goods: data.data.data.filter(v=>v.op_num>0).map(v=>{
                        return {
                            id: v.id,
                            num: v.op_num
                        }
                    })
                }
                
                if(payload.goods.length  == 0){
                    data.loading = false;
                    onmessage({success:false, message:'没有选择商品'});
                    return;
                }

                useSocket().then(socket=>socket.rpc('move_to_store', payload)).then(res=>{
                    onmessage(res);
                    changed = false;
                    data.dialogVisible = false;
                    data.loading = false;
                }).catch((msg)=>{
                    data.loading = false;
                    onmessage(msg);
                });
            },
            onCancel:()=>{
                data.dialogVisible = false;
            },
            init:()=>{
            },
            beforeClose:(next)=>{
                next();
            },
            finalThings:()=>{
                changed && props.q.resolve(true);
                props.done()
            },
            onSearch:(item)=>{

            },
            onRemoveItem:(item)=>{
                ElMessageBox.confirm(`确定要删除"${item.name}"吗?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    useSocket().then(socket=>socket.rpc('rmsel',{store_id:storeId,goods_id:item.id})).then(res=>{
                        changed = true;
                        data.data.data.splice(data.data.data.indexOf(item),1);
                    }).catch(() => {});
                }).catch(() => {
                });
            },
            ExtraSelect:()=>{
                console.log({storeId, mh:data.h, isRack,stores:props.stores});
                UiShowDialog(ExtraSelectDialog, {storeId, mh:data.h, isRack,stores:props.stores}).then(res=>{
                    renewSelected();
                }).catch(res=>{
                    renewSelected();
                })
            },
            filter:(v,r,c)=>{
                console.log('filter:', v,r,c)
            }
        };

        useSocket().then(socket=>socket.rpc('sel.get',{store_id:storeId, target_id:data.data.target_id, with_goods:true}).then(res=>{
            res.data.forEach(v=>{v.op_num=0;})
            data.data.data = res.data;
        }).catch(res=>{

        }))
        return {
            ...toRefs(data),
            ...methods,
            rules
        }
    }
}
</script>
<style lang="scss">
.ui-rackon-dlg{
    width:60rem;max-width: 60rem;
    .el-dialog__body{
        padding: .5rem 1rem;
        .memo-class{
            min-width:30rem;
        }
        .op-num-ipt{
            max-width: 6rem;
            .el-input__wrapper{padding-left:20px;padding-right:20px;}
            .el-input-number__decrease,.el-input-number__increase{
                width:20px;
            }
        }
    }
}
</style>